﻿namespace EyeOpen.IO.Ports
{
	using System;
	using System.Threading;

	public class Modem 
		: Rs232
	{
		public Modem(IPort port, ILogger logger, string pin, string puk)
			: base(port, logger)
		{
			Pin = pin;
			Puk = puk;
		}

		public string Pin { get; private set; }

		public string Puk { get; private set; }

		public override void OpenChannel()
		{
			Logger.WriteLine("Opening channel " + Type + "...");

			try
			{
				OpenRs232Channel();
				SwitchOn();

				State = ChannelState.Open;
				Logger.WriteLine("State: " + State);
			}
			catch (Exception ex)
			{
				Logger.WriteLine("OpenChannel Exception: " + ex.Message);

				State = this.IsOpen ? ChannelState.Open : ChannelState.Closed;
				Logger.WriteLine("State: " + State);
			}
		}

		public override void CloseChannel()
		{
			Logger.WriteLine("Closing channel " + Type + "...");

			try
			{
				SwitchOff();
				this.CloseRs232Channel();

				State = ChannelState.Closed;
				Logger.WriteLine("State: " + State);
			}
			catch (Exception ex)
			{
				Logger.WriteLine("OpenChannel Exception: " + ex.Message);

				State = this.IsOpen ? ChannelState.Open : ChannelState.Closed;
				Logger.WriteLine("State: " + State);
			}
		}

		private void SwitchOn()
		{
			Port.RtsEnable = false;
			Thread.Sleep(500);

			Port.RtsEnable = true;
			Thread.Sleep(2000);

			Port.RtsEnable = false;
			Thread.Sleep(500);
		}

		private void SwitchOff()
		{
			Port.DtrEnable = false;
			Thread.Sleep(500);

			Port.DtrEnable = true;
			Thread.Sleep(2000);

			Port.DtrEnable = false;
			Thread.Sleep(500);
		}
	}
}